package cn.com.bonc.khjy.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:dataSource.properties")
@MapperScan(basePackages = "cn.com.bonc.khjy.date.mapper.dataSource2",sqlSessionFactoryRef = "getSqlSessionFactory2")
public class SecondaryDataSourceConfig {

    private static Logger logger = LoggerFactory.getLogger(SecondaryDataSourceConfig.class);
    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource(){
        logger.debug("创建第二个数据库连接池。。。");
        return DataSourceBuilder.create().build();
    }

    @Bean("getSqlSessionFactory2")
    public SqlSessionFactory getSqlSessionFactory2(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
        logger.debug("创建第二个数据库连接池的SqlSessionFactory");
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 配置mapper.xml的位置
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:data/mapper/dataSource2"));
        return factoryBean.getObject();
    }

    @Bean("getSqlSessionTemplate2")
    public SqlSessionTemplate getSqlSessionTemplate2(@Qualifier("getSqlSessionFactory2") SqlSessionFactory sqlSessionFactory){
        logger.debug("创建第二个数据库连接池的SqlSessionTemplate");
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
